package com.aivin.lib_widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;


/**
 *  这个控件 只能简单使用 ，还有很多问题。
 *  对数字、英文 、换行  等 没处理。
 *  有时间再优化
 */
public class TextViewVertical extends View {
    private String text = "测试" ;
    private Paint paint;

    public TextViewVertical(Context context) {
        super(context);
        init();
    }

    public TextViewVertical(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setTextSize(80);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.FILL);
        paint.setAntiAlias(true);
        paint.setTextAlign(Paint.Align.CENTER);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
         int viewHeight = measureHeight(heightMeasureSpec);
        int viewWidth = measureWidth(widthMeasureSpec);
        // 这个方法决定了当前View的大小
        setMeasuredDimension(viewWidth, viewHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        this.setBackgroundColor(Color.RED);
        float oneWordWidth = getOneWordWidth();
        float oneWordHeight = getOneWordHeight();

        for (int i = 0; i < text.length(); i++) {
            String str = String.valueOf(text.charAt(i));
            drawText(oneWordWidth, oneWordHeight,  0, i, str, canvas);
        }
    }



    private int measureWidth(int measureSpec) {
        return (int) getOneWordWidth();
    }

    int topPadding = 30 ;
    private int measureHeight(int measureSpec) {
        int result = (int) (getOneWordHeight() * text.length())   ;
        result =  result  + topPadding  ;
        return result;
    }


    /**
     * 设置文字
     */
    public void setText(String text) {
        this.text = text;
        requestLayout(); // 不调用这个 的话 ，setMeasuredDimension 不生效，不知道为啥
    }


    private float getOneWordWidth() {
        return paint.measureText("中") ;
    }

    private float getOneWordHeight() {
        Rect rect = new Rect();
        paint.getTextBounds("中", 0, 1, rect);
        return rect.height()  ;
    }



    /**
     * @param currentCol 列
     * @param currentRow  行
     */
    private void drawText(float oneWordWidth, float oneWordHeight, int currentCol, int currentRow, String str, Canvas canvas) {
        RectF   rectF = new RectF(0,
                currentRow * oneWordHeight + topPadding,
                 oneWordWidth,
                currentRow * oneWordHeight + oneWordHeight +topPadding);
        canvas.drawText(str, rectF.centerX(), rectF.centerY(), paint);
    }
}